package com.gb.demand.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

import static java.lang.Short.MAX_VALUE;
import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * @author luohuiqi
 * @Description:
 * @Date: 2019/7/14 1:40
 */
public class FileUtil {

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);

    }

    public static void exportExcelByTemplate(String fileName, String templateFileName, Map<String, Object> dataMap) {
        ClassPathResource resource = new ClassPathResource("templete/" + templateFileName);
        TemplateExportParams params = new TemplateExportParams(resource.getPath());
        Workbook workbook = ExcelExportUtil.exportExcel(params, dataMap);
        // 写入数据
        if (workbook != null) {
            downLoadAndCloseExcel(fileName, workbook);
        }
    }


    public static void exportWordByTemplate(String fileName, Map<String, Object> dataMap) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try (ServletOutputStream sos = response.getOutputStream()) {
            XWPFDocument xwpfDocument = WordExportUtil.exportWord07("templete/" + fileName, dataMap);
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            xwpfDocument.write(sos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        exportParams.setHeight((short) 14);
//		exportParams.setStyle(ExcelStyleUtil.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        // 添加合计
        Sheet sheet = workbook.getSheetAt(0);
        // 设置最后一列的格式
        Row finalRow = sheet.getRow(sheet.getLastRowNum());
        Row sheetRow = sheet.getRow(sheet.getLastRowNum() - 1);
        finalRow.setHeight(sheetRow.getHeight());

        // 新建3行,分别为填表人，审核人，以及报告日期（导出时间）
        Row row = sheet.createRow(sheet.getLastRowNum() + 1);
        row.setHeight((short) (MAX_VALUE / 80));
        Cell cell00 = row.createCell(0);
        cell00.setCellValue("填表人:");
        Cell cell02 = row.createCell(2);
        cell02.setCellValue("审核人:");
        Cell cell05 = row.createCell(5);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.now();
        String formattedDateTime = dateTime.format(formatter);
        cell05.setCellValue("报告日期: " + formattedDateTime);
        // 写入数据
        if (workbook != null) {
            downLoadAndCloseExcel(fileName, workbook);
        }
    }

    private static void downLoadAndCloseExcel(String fileName, Workbook workbook) {
        ServletOutputStream sos = null;
        try {
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
//			response.setContentType("application/x-msdownload");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            sos = response.getOutputStream();
            workbook.write(sos);
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static void downLoadAndCloseWord(String fileName, XWPFDocument xwpfDocument) {
        ServletOutputStream sos = null;
        try {
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//			response.setContentType("application/x-msdownload");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            sos = response.getOutputStream();
            xwpfDocument.write(sos);
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null) {
            downLoadAndCloseExcel(fileName, workbook);
        }
    }

    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

}
